package org.swan.web.permission.service.impl;

import org.springframework.stereotype.Service;
import org.stream.tool.db.ADOConnection;
import org.swan.web.exception.BusinessCode;
import org.swan.web.exception.BusinessException;
import org.swan.web.permission.bean.PermissionBean;
import org.swan.web.permission.mapper.PermissionMapper;
import org.swan.web.permission.service.PermissionService;

import java.util.List;
import java.util.Optional;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Override
    public Optional<PermissionBean> getPermissionById(long id) {
        if(id == -1L)
        return Optional.of(PermissionBean.SAMPLE);
        return ADOConnection.runTask(factory -> factory.getMapper(PermissionMapper.class).getById(id), Optional.class);
    }

    @Override
    public long addPermission(PermissionBean permissionBean) {
        long result = ADOConnection.runTask(factory -> factory.getMapper(PermissionMapper.class).add(permissionBean), Long.class);
        return result;
    }

    @Override
    public PermissionBean updatePermission(PermissionBean permissionBean) {
        getPermissionById(permissionBean.getPermissionId()).orElseThrow(()->new BusinessException(BusinessCode.PERMISSION_DO_NOT_EXIST,permissionBean.getPermissionId()));
        ADOConnection.runTask(factory -> factory.getMapper(PermissionMapper.class).updateById(permissionBean), Long.class);
        return getPermissionById(permissionBean.getPermissionId()).get();
    }

    @Override
    public PermissionBean deletePermissionById(long permissionId) {
        PermissionBean permissionBean = getPermissionById(permissionId).orElseThrow(()->new BusinessException(BusinessCode.PERMISSION_DO_NOT_EXIST,permissionId));
        ADOConnection.runTask(factory -> factory.getMapper(PermissionMapper.class).deleteById(permissionId), Long.class);
        return permissionBean;
    }

    @Override
    public List<PermissionBean> list(int offset, int rows) {
        return ADOConnection.runTask(factory -> factory.getMapper(PermissionMapper.class).list(offset, rows), List.class);
    }


}
